// @ts-nocheck
import $fetch from '@system.fetch'
import utils from '../helper/utils';
import config from '../config';
import { getToken } from './storage';
import prompt from '@system.prompt';

/**
 * 接口请求
 * @param {Object} params 请求参数
 * @returns Promise
 */
const fetch = (params) => {
    return new Promise(async (resolve, reject) => {
        const { url, data, method, ...options } = params;
        const token = await getToken();
        console.log("fetch=", params)
        if (utils.isBrowser()) {
            const requestOptions = {
                ...options,
                method,
                headers: {
                    'Content-Type': 'application/json;charset=utf-8',
                    authorization: `Bearer ${token}`
                }
            };
            if (method.toLowerCase() === 'post') {
                requestOptions.body = JSON.stringify(data || {});
            }
            window.fetch(`${config.API_HOST}${url}`, requestOptions).then(res => res.json()).then(res => {
                const { errorCode, errorMessage, success, data } = res;
                console.log("fetch response=", res);
                if (success) {
                    resolve(res.data);
                } else {
                    prompt.showToast({ message: errorMessage });
                    reject({ err_code: errorCode, err_msg: errorMessage });
                }
            }).catch((err) => {
                prompt.showToast({ message: '网络错误，请检查网络后重试', duration: 1 });
                reject({err_code: 500, err_msg: err});
            });
        } else {
            $fetch.fetch({
                ...params, ... {
                    success: (_res) => {
                        const res = JSON.parse(_res.data)
                        const { errorCode, errorMessage, success, data } = res;
                        if (success) {
                            resolve(res.data);
                        } else {
                            prompt.showToast({ message: errorMessage });
                            reject({ err_code: errorCode, err_msg: errorMessage });
                        }
                    },
                    fail: (err) => {
                        prompt.showToast({ message: '网络错误，请检查网络后重试', duration: 1 });
                        reject({err_code: 500, err_msg: err});
                    }
                }, ...{
                    header: {
                        authorization: `Bearer ${token}`,
                        'Content-Type': 'application/json;charset=utf-8',
                    }
                }, ...{
                    url: `${config.API_HOST}${url}`
                }
            });
        }
    })
};



export default {
    fetch,
}